local sin = math.sin
local cos = math.cos
local rad = math.rad
local sqrt = math.sqrt
require("fishenum")

local bullet = {}

--[[
	config = {
		-- Id = 0,	-- 编号，创建实体时生成随机不重复的值
		Type = 0,	-- 类型，通过配置可以取名字，描述等信息
		R = 0,		-- 伤害半径值，目前判定为圆形
		PosX = 0,	-- 圆心位置X
		PosY = 0,	-- 圆心位置Y
		Angle = 0,	-- 转动角度
		Stat = 0,	-- 状态，-1 死亡 1 存活
		Level = 0,	-- 等级
		Speed = 0,	-- 移动速度
		Damage = 0,	-- 伤害值
		Rid = 0,	-- 玩家id
		Target = 0,	-- 追踪目标
	} 
--]]
local function init(entity, dinit, launcher)
	entity.Id 		= dinit.Id
	entity.Type 	= dinit.Type
	entity.R 		= dinit.R
	entity.PosX 	= dinit.PosX
	entity.PosY 	= dinit.PosY
	entity.Angle 	= dinit.Angle
	entity.Stat 	= dinit.Stat or EEntityStat.ALIVE
	entity.Level 	= dinit.Level
	entity.Speed 	= dinit.Speed
	entity.Damage	= dinit.Damage or 1
	entity.Rid		= dinit.Rid
	entity.Target	= dinit.Target
	entity.Launcher = launcher
end

function bullet:new(s2csync, s2csyncex, dinit, launcher, obj)
	local entity = obj or {}
	init(entity, dinit, launcher)
	entity.s2csync = s2csync
	entity.s2csyncex = s2csyncex

	setmetatable(entity, self)
	self.__index = self
	entity:sync_ex()
	return entity
end

function bullet:die()
	self.Speed = 0
	self.Stat = EEntityStat.DEAD
	-- self:sync()	-- 现在客户端在同房间每个玩家那里都做了碰撞检测（会移除子弹），这里不用同步了
end

function bullet:check_edge(screen)
	if self.PosX <= 0 then
	elseif self.PosX >= screen.Width then
		self:turn(360 - self.Angle)
	elseif self.PosY <= 0 or self.PosY >= screen.Height then
		if self.Angle >= 0 and self.Angle <= 180 then
			self:turn(360 - self.Angle - 180)
		elseif self.Angle > 180 then
			self:turn(360 - self.Angle + 180)
		end
	end
end

function bullet:move(screen)
	if self.Speed == 0 or self.Stat == EEntityStat.DEAD then
		return
	end
	local speed = self.Speed
	local angle = self.Angle
	self.PosX = self.PosX + speed*sin(rad(angle))
	self.PosY = self.PosY + speed*cos(rad(angle))

	self:check_edge(screen)

	-- self:sync()
end

-- 因为只碰撞第一个，所以不需要再做爆炸碰撞检测
function bullet:collision_detection(target)
	local collided = false
	local len = sqrt((self.PosX - target.PosX)^2 + (self.PosY - target.PosY)^2)
	if len <= (self.R + target.R) then
		collided = true
		self:die()
		return collided, target, len
	end
	return collided
end

-- 子弹应该不用转弯
function bullet:turn(angle)
	self.Angle = self.Angle + angle
	self:sync_ex()
end

function bullet:set_target(target)
	self.Target = target
end

function bullet:sync()
	if self.s2csync then
		self:s2csync()
	end
end

-- 转发数据
function bullet:sync_ex()
	if self.s2csyncex then
		self:s2csyncex()
	end
end

return bullet
